import React, { useState, useEffect } from "react";
import styles from "./index.module.less";
import getClock from "@utils/getClock";

const Clock = () => {
    const [date, setDate] = useState(getClock());

    useEffect(() => {
        let start = 0;
        let timer = null;
        function loop() {
            let end = Date.now();
            if (end - start >= 1000) {
                // 确保原状态的不可变性
                let c = Object.assign({}, getClock());
                setDate(c);
                start = end;
            }
            timer = requestAnimationFrame(loop);
        }
        loop();
        return () => {
            cancelAnimationFrame(timer);
        };
    }, []);
    return (
        <div className={styles.clock}>
            <p className={styles.p1}>
                {date.year}年 {date.month}月{date.day}日
            </p>
            <p className={styles.p1}>
                {date.hour}:{date.minutes}:{date.seconds} 星期{date.week}
            </p>
        </div>
    );
};

export default Clock;
